﻿using HostAssistantBLL;
using HostAssistantCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HostAssistant
{
    public partial class editsites : U1Form
    {
        string[] _csiterow = null;
        public editsites(string[] csiterow)
        {
            InitializeComponent();
            _csiterow = csiterow;
            NLogger.Info("csiterow:"+ JsonHelper.SerializeObject(csiterow) );
         
            chkyes.Properties.RadioGroupIndex = 1;
            chkyes.Checked = true;
            chkno.Properties.RadioGroupIndex = 1;
            txtphppath.Visible = simpleButton4.Visible = false;
            txtphppath.ReadOnly = true;
            lblhid.Visible = false;
        }
        private void addsites_Load(object sender, EventArgs e)
        {
          //  this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath");
             
            TextBoxToolV2.SetWatermark(txtcpu, "不限CPU");

            TextBoxToolV2.SetWatermark(txtdk, "不限带宽");

            TextBoxToolV2.SetWatermark(txtljs, "不限连接数");

            TextBoxToolV2.SetWatermark(txtnc, "不限内存");
            netv();



            txtsname.Text = _csiterow[1];
            txtspath.Text = _csiterow[3];
            txtdm.Text = _csiterow[2];
            txtsy.Text = _csiterow[16];
            cstatus.Text= ( !string.IsNullOrWhiteSpace( _csiterow[15])?"PHP":"ASP.NET");


            if(cstatus.Text== "ASP.NET")
            {
                if (_csiterow[12] == "v4.0")
                {
                    cmbv.SelectedIndex = 1;
                }
            }
            else
            {

                txtphppath.Visible = true;
                txtphppath.Text = _csiterow[15];
            }


            txtdk.Text = _csiterow[8];

            txtljs.Text = _csiterow[9];


            txtcpu.Text = _csiterow[10];

            txtnc.Text = _csiterow[11];


            labelControl13.Text = _csiterow[4];

            var slist=  sitebll.GetsiteList();
            var sf= slist.FirstOrDefault(o => o.name == txtsname.Text);
            labelControl14.Text = sf?.ftpname??"--";

            if (_csiterow[14] == "Started")
                chkyes.Checked = true;

            if (_csiterow[14] == "Stopped")
                chkno.Checked = true;
         



        }

        /// <summary>
        /// 获取net版本
        /// </summary>
        void netv()
        {
            cmbv.Properties.Items.Clear();
          
            string netv2 = "";
            string netv4 = "";

            try
            {
                var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
                foreach (string keyname in key.GetSubKeyNames())
                {
                    string netversion = keyname.Substring(0, 2);
                    if (netversion == "v2")
                    {

                        netv2 = "v2.0.50727";
                    }
                    if (netversion == "v4")
                    {
                        try
                        {
                            netv4 = "v" + Environment.Version.ToString();

                        }
                        catch (Exception ex)
                        {
                            NLogger.Error(ex.ToString());
                        }
                    }
                    if (netv2 == "" && netv4 == "")
                    {
                        DirectoryInfo NetFolder = new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework");
                        //遍历文件夹
                        foreach (DirectoryInfo sonFolder in NetFolder.GetDirectories())
                        {
                            if (sonFolder.Name.Contains("v2.0"))
                            {
                                netv2 = "v2.0.50727";
                            }
                        }
                        netv4 = "v" + Environment.Version.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                DirectoryInfo NetFolder = new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework");
                //遍历文件夹
                foreach (DirectoryInfo sonFolder in NetFolder.GetDirectories())
                {
                    if (sonFolder.Name.Contains("v2.0"))
                    {
                        netv2 = "v2.0.50727";
                    }
                }
                netv4 = "v" + Environment.Version.ToString();
            }
            if (netv2.Trim().ToString() != "")
            {



                cmbv.Properties.Items.Add(netv2);
                cmbv.Text = netv2;

            }
            if (netv4.Trim().ToString() != "")
            {

                cmbv.Properties.Items.Add(netv4);

                if (cmbv.Text == "")
                    cmbv.Text = netv4;
            }
        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {

          
            this.Dispose();
        }

        /// <summary>
        /// 选择路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                txtspath.Text = foldPath;


            }
        }

        private void txtsname_EditValueChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {

           

            if (string.IsNullOrWhiteSpace(txtdm.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("绑定域名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            if (string.IsNullOrWhiteSpace(txtsy.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("默认首页不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (cstatus.Text == "PHP")
            {
                if (string.IsNullOrWhiteSpace(txtphppath.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("PHP路径不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }


                if (!File.Exists(txtphppath.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("PHP文件不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            if (!chkyes.Checked  && !chkno.Checked)
            {

                DevExpress.XtraEditors.XtraMessageBox.Show("状态不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }





            try
            {
                splashScreenManager1.ShowWaitForm();
                splashScreenManager1.SetWaitFormCaption("请等待");
                splashScreenManager1.SetWaitFormDescription("加载中...");


                int iistouch = UtilFactory.IISTouch();
                int errorCode = ErrorCode.siteStart;
                AddSiteUtil addsiteUtil = new AddSiteUtil();
                //启动站点
                if (iistouch == 2)
                {
                    //iis7
                    if (chkno.Checked == true)
                    {
                        errorCode = addsiteUtil.siteStord(txtsname.Text);

                    }
                    else
                    {
                        errorCode = addsiteUtil.siteStart(txtsname.Text);

                    }



                }
                if (iistouch == 1)
                {
                    //iis6
                    if (chkno.Checked == true)
                    {
                        errorCode = addsiteUtil.isiteStord(txtsname.Text);


                    }
                    else
                    {
                        errorCode = addsiteUtil.isiteStart(txtsname.Text);

                    }
                }
                //if (errorCode == ErrorCode.siteStart)
                //{


                //    splashScreenManager1.CloseWaitForm();
                //    DevExpress.XtraEditors.XtraMessageBox.Show("操作成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


                //}
                //if (errorCode == ErrorCode.siteStateError)
                //{


                //    splashScreenManager1.CloseWaitForm();
                //    DevExpress.XtraEditors.XtraMessageBox.Show("操作失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


                //}



                OpHelper.CallWithTimeout(Addmssql, 10000);

            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {

             



                if (lblhid.Text == "1")
                {
                    lblhid.Text = "0";
                    Form1 f1 = (Form1)this.Owner;
                    f1.op("站点列表");
                    this.Dispose();
                }

            }





            
        }


        void Addmssql()
        {
          

          
             
           
                /*
                 * 获取用户输入
                 */
                SiteInfo siteinfo = new SiteInfo();
                siteinfo.SiteName = this.txtsname.Text.Trim().ToString();//站点名

                siteinfo.PhysicalPath = this.txtspath.Text.Trim().ToString();//物理路径
                siteinfo.LogPath = siteinfo.PhysicalPath;


                /*
                 * 处理用户输入域名
                 */
                if (this.txtdm.Text.Trim().ToString() != _csiterow[2])
                {
                    List<string> bindings = new List<string>();
                    string[] cbindings = this.txtdm.Text.Split(",".ToCharArray());
                    foreach (string binding in cbindings)
                    {
                        int length = binding.Split(":".ToCharArray()).Length;
                        if (length == 1)
                        {
                            bindings.Add(binding + ":" + "80");
                        }
                        else
                        {
                            bindings.Add(binding);
                        }
                    }
                    siteinfo.Bindings = bindings;//绑定域名+端口
                }
                else
                {
                    siteinfo.Bindings = null;//绑定域名+端口
                }

           // var slist = sitebll.GetsiteList();
          //  var sf = slist.FirstOrDefault(o => o.name == txtsname.Text);


            /*
             * 获取ftp账号密码
             */
            //if (!string.IsNullOrWhiteSpace(sf.ftpname))
            //    {
            //        siteinfo.Ftpass = sf. this.ftppass.Text.Trim().ToString();
            //        siteinfo.Password = this.ftppass.Text.Trim().ToString();//密码

            //    }
            //    else//如果用户不设置FTP那么用户密码为用户名
            //    {
                    siteinfo.Ftpass = "";
                    siteinfo.Password = "";
            //}
            /*
             * 获取net版本
             */
            string netversion = cmbv.Text;
            
                string version = "";
                if (cstatus.Text == "PHP")
                {
                    version = "";
                }
                else
                {
                    version = netversion.Substring(0, 4);
                    siteinfo.NetVersion = version;
                }

            //if (this.SelectedValue.SelectedIndex == 0)
            //{
            //    siteinfo.NetVersion = csiterow[12];
            //}
            //else
            //{
            //    siteinfo.NetVersion = version;
            //}



            /*
             * 获取PHP路径
             */
            if (cstatus.Text == "ASP.NET")
            {
                    siteinfo.Phppath = "";
                }
                else
                {
                    string[] yy = _csiterow;
                    if (this.txtphppath.Text.ToString() != _csiterow[15])
                    {
                        siteinfo.Phppath = this.txtphppath.Text.Trim().ToString();
                      

                }
                    else
                    {
                        siteinfo.Phppath = "";
                    }
                }
                /*
                 * 处理用户输入默认首页
                 */
                if (this.txtsy.Text.Trim().ToString() != _csiterow[16])
                {
                    List<string> defaultDocuments = new List<string>();
                    string pages = this.txtsy.Text.Trim().ToString();
                    if (pages != "")
                    {
                        string[] homepages = pages.Split(",".ToArray());
                        foreach (string defaultDocument in homepages)
                        {
                            defaultDocuments.Add(defaultDocument);
                        }
                    }
                    siteinfo.DefaultDocuments = defaultDocuments;
                }
                else
                {
                    siteinfo.DefaultDocuments = null;
                }



            ////if (this.maxbands.Text != "不做限制" && this.maxbands.Text != "-1M" && this.maxbands.Text != "-1")
            ////{
            ////    siteinfo.MaxBandwidth = this.maxbands.Text.Substring(0, this.maxbands.Text.Length - 1);//最大带宽
            ////}
            ////else
            ////{
            ////    siteinfo.MaxBandwidth = "0";
            ////}
            ////if (this.maxconnections.Text != "不做限制")
            ////{
            ////    siteinfo.MaxConnections = this.maxconnections.Text.Substring(0, this.maxconnections.Text.Length - 1); ;//最大连接数
            ////}
            ////else
            ////{
            ////    siteinfo.MaxConnections = "0";
            ////}
            ////if (this.cpulimit.Text != "不做限制")
            ////{
            ////    siteinfo.Cpulimit = this.cpulimit.Text.Substring(0, this.cpulimit.Text.Length - 1); ;//最大CPU
            ////}
            ////else
            ////{
            ////    siteinfo.Cpulimit = "0";
            ////}
            ////if (this.memory.Text != "不做限制")
            ////{
            ////    siteinfo.Memeroy = this.memory.Text.Substring(0, this.memory.Text.Length - 1); ;//最大Memeory
            ////}
            ////else
            ////{
            ////    siteinfo.Memeroy = "0";
            ////}

            if (!string.IsNullOrWhiteSpace(this.txtdk.Text))
            {
                long tmaxbands = Convert.ToInt64(this.txtdk.Text.Trim());
                if (tmaxbands > 4095)
                {
                    siteinfo.MaxBandwidth = "0";
                }
                else
                {
                    siteinfo.MaxBandwidth = this.txtdk.Text.Trim();//最大带宽
                }
            }
            else
            {
                siteinfo.MaxBandwidth = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtljs.Text))
            {
                long tmaxconnections = Convert.ToInt64(this.txtljs.Text.Trim());
                if (tmaxconnections > 4294967295)
                {
                    siteinfo.MaxConnections = "0";
                }
                else
                {
                    siteinfo.MaxConnections = this.txtljs.Text.Trim(); //最大连接数
                }
            }
            else
            {
                siteinfo.MaxConnections = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtcpu.Text))
            {
                siteinfo.Cpulimit = this.txtcpu.Text.Trim(); ;//最大CPU
            }
            else
            {
                siteinfo.Cpulimit = "0";
            }
            if (!string.IsNullOrWhiteSpace(this.txtnc.Text))
            {
                siteinfo.Memeroy = this.txtnc.Text.Trim();//最大Memeory
                string y = this.txtnc.Text;
                string x = siteinfo.Memeroy;
            }
            else
            {
                siteinfo.Memeroy = "0";
            }



            siteinfo.Sstate = "off";
                siteinfo.Sstype = "site";
                siteinfo.Username = _csiterow[6];

                /*---- delete site's ftp ----*/
                //if (ftp_state && !this.ftpcheckbox.Checked)
                //{
                //    //删除FTP
                //    iismanager.DeleteFtp(siteinfo.SiteName);
                //}
                /*--- update ----*/
               // ftp_state = this.ftpcheckbox.Checked;
                int errorCode = ErrorCode.SetSucceed;
                IISManager iismanager = new IISManager();
                errorCode = iismanager.Manager(new string[] { "SETSITE", "oh" }, siteinfo);
            /*
             * 显示完成提示
             */
            //MessageTips messageTips = new MessageTips(this, MessageTips.MessageTipsStyle.info, ErrorCode.getResult(errorCode));//创建提示窗体
            //messageTips.StartPosition = FormStartPosition.Manual;//设置子窗体位置类型
            //sizeInit(messageTips, 260, 150);//设置窗体位置
            //messageTips.ShowDialog(this);//显示窗体


            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show(ErrorCode.getResult(errorCode), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if(errorCode== ErrorCode.SetSucceed)
            {
                lblhid.Text = "1";
            }


        }
        /// <summary>
        /// 随机密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
          
        }

      

    

        /// <summary>
        /// 类型切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cstatus_SelectedValueChanged(object sender, EventArgs e)
        {
           

            if(cstatus.Text=="PHP")
            {
                cmbv.Properties.Items.Clear();
                cmbv.Properties.Items.Add("5.2");
                cmbv.Text = "5.2";
                cmbv.Properties.Items.Add("5.3");
                cmbv.Properties.Items.Add("5.4");
                cmbv.Properties.Items.Add("5.6");

                txtphppath.Visible = simpleButton4.Visible = true;

                txtphppath.Text = "";

                txtphppath.Text = @"C:\php\php" + cmbv.Text.Replace(".", "") + @"\php-cgi.exe";

            }
            else
            {
             
                netv();


                txtphppath.Visible = simpleButton4.Visible = false;

                txtphppath.Text = "";
            }

        }

        /// <summary>
        /// 选择php cgi exe  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {

            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*exe*)|*.exe*"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径                
                txtphppath.Text = file;

            }

        }

        private void comboBoxEdit1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cstatus.Text == "PHP")
            {
                txtphppath.Text = @"C:\php\php"+ cmbv .Text.Replace(".","")+ @"\php-cgi.exe";
            }

               
            }

        private void txtcpu_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtdk_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtljs_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtnc_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                e.Handled = false;
            }
        }

        private void txtsname_MouseLeave(object sender, EventArgs e)
        {
            //string s = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath");


            //if (this.txtspath.Text.ToLower() == System.Configuration.ConfigurationManager.AppSettings.Get("sitepath").ToLower())
            //{
            //    this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath") + "\\" + this.txtsname.Text + "\\wwwroot";
            //}
            //else
            //{
            //    if (this.txtspath.Text.Contains(s))
            //    {
            //        this.txtspath.Text = System.Configuration.ConfigurationManager.AppSettings.Get("sitepath") + "\\" + this.txtsname.Text + "\\wwwroot";

            //    }
            //}
        }


        #region 备份站点
        /// <summary>
        /// 备份站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click_1(object sender, EventArgs e)
        {

            try
            {
                OpHelper.CallWithTimeout(baksite, 300000);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }



        }


        void baksite()
        {
            splashScreenManager1.ShowWaitForm();
            splashScreenManager1.SetWaitFormCaption("请等待");
            splashScreenManager1.SetWaitFormDescription("加载中...");

            var set = Data<HostAssistantCore.PathSet>.GetInstance().GetModelList("select *  from PathSet", null).FirstOrDefault();
            if (set == null)
            {
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show("请先到“系统配置”进行相关参数配置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }




            var slist = sitebll.GetsiteList();
            var sf = slist.FirstOrDefault(o => o.name == txtsname.Text);
            string bakDic= set.SiteBakPath + "\\" + sf.name+"\\";
            if(!Directory.Exists(bakDic))
            {
                Directory.CreateDirectory(bakDic);
            }


            ZipClass.ZipDirectory(sf.path, bakDic, sf.name + DateTime.Now.ToString("yyyyMMddHHmmss"));


            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show("站点备份完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        } 
        #endregion




        /// <summary>
        /// 还原站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click_1(object sender, EventArgs e)
        {
            var set = Data<HostAssistantCore.PathSet>.GetInstance().GetModelList("select *  from PathSet", null).FirstOrDefault();
            if (set == null)
            {
              
                DevExpress.XtraEditors.XtraMessageBox.Show("请先到“系统配置”进行相关参数配置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }
           

            rollbaksite f2 = new rollbaksite(txtsname.Text);
            f2.ShowDialog(this);
            return;
            try
            {
                OpHelper.CallWithTimeout(rollbaksite, 300000);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        void rollbaksite()
        {
            splashScreenManager1.ShowWaitForm();
            splashScreenManager1.SetWaitFormCaption("请等待");
            splashScreenManager1.SetWaitFormDescription("加载中...");




            var set = Data<HostAssistantCore.PathSet>.GetInstance().GetModelList("select *  from PathSet", null).FirstOrDefault();
            if (set == null)
            {
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show("请先到“系统配置”进行相关参数配置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }




            var slist = sitebll.GetsiteList();
            var sf = slist.FirstOrDefault(o => o.name == txtsname.Text);
            string bakDic = set.SiteBakPath + "\\" + sf.name + "\\";
            if (!Directory.Exists(bakDic))
            {
                Directory.CreateDirectory(bakDic);
            }


            ZipClass.ZipDirectory(sf.path, bakDic, sf.name + DateTime.Now.ToString("yyyyMMddHHmmss"));


            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show("站点备份完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

    }
}
